package com.carrental.servlet;

import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.carrental.entity.CarRental;
import com.carrental.entity.User;
import com.carrental.service.CarRentalService;

/**
 * Servlet implementation class CarRentalAddServlet
 */
@WebServlet("/CarRentalAddServlet")
public class CarRentalAddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	CarRentalService carRentalService;
       
    /**
     * @throws Exception 
     * @see HttpServlet#HttpServlet()
     */
    public CarRentalAddServlet() throws Exception {
        super();
        carRentalService = new CarRentalService();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String carId = request.getParameter("carId");
		String username = ((User) request.getSession().getAttribute("user")).getUsername();
		String rentalNum = request.getParameter("rentalNum");
		String rentalTotal = request.getParameter("rentalTotal");
		String rentalStartDatetime = request.getParameter("rentalStartDatetime");
		String rentalEndDatetime = request.getParameter("rentalEndDatetime");
		
		CarRental carRental = new CarRental();
		carRental.setId(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date()));
		carRental.setCarId(carId);
		carRental.setUsername(username);
		carRental.setRentalNum(Integer.parseInt(rentalNum));
		carRental.setRentalTotal(Double.valueOf(rentalTotal));
		carRental.setRentalStartDatetime(Date.valueOf(rentalStartDatetime));
		carRental.setRentalEndDatetime(Date.valueOf(rentalEndDatetime));
		carRental.setCreateDatetime(new Timestamp(new java.util.Date().getTime()));
		
		System.out.println("添加订单：" + carRental);
		
		try {
			carRentalService.add(carRental);
			response.sendRedirect("carRentalList.jsp");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
